package Controller;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import Model.Data;
import Model.Encryption;
import Model.RequestHandler;

public class Request extends Thread 
{
	private Socket m_Socket;
	private Encryption m_Enc;

	public Request(Socket connSocket, Encryption enc) 
	{
		m_Socket = connSocket;
		m_Enc = enc;
	}
	
	@Override
	public void run()
	{
		
		DataInputStream in = null;
		DataOutputStream out = null;
		
		try
		{
			// client's input/output
			in = new DataInputStream(m_Socket.getInputStream());
			out = new DataOutputStream(m_Socket.getOutputStream());
        
			// get client's request
			byte[] message = null;
			int length = in.readInt();
			if(length>0) {
			    message = new byte[length];
			    in.readFully(message, 0, message.length); 
			}
	        
	        // process request
			byte[] msg = m_Enc.decrypt(message);			
	        RequestHandler handler = new RequestHandler(msg);	        
	       
	        byte[] result = m_Enc.decrypt(Data.getInstance().pull(handler.getMapKey()));
	        
	        // send data back
	        out.writeInt(result.length); 
	        out.write(result);
	        
	        // add new data
        	handler.send();	        
		}
		catch(Exception e)
		{

		}
		finally
		{
			try
			{
				out.close();
			}
			catch(Exception e)
			{
				
			}
			
			try
			{
				in.close();
			}
			catch(Exception e)
			{
				
			}
			
			try
			{
				m_Socket.close();
			}
			catch(Exception e)
			{
				
			}
		}
	}
}
